import decimal
import sys
from PyQt5.QtWidgets import QProgressBar, QFileDialog, QTableWidgetItem, QGridLayout, QDialog, QTableWidget, \
    QPushButton, QVBoxLayout, QWidget, QTabWidget, QApplication, QMenu, QAction
from PyQt5.QtGui import QColor, QBrush, QClipboard
from PyQt5.QtCore import Qt
import pandas
import re
import os
from collections import Counter
import UI_5



def remove_non_digit(value: str) -> str:
    return re.sub(r'\D', '', value)


def remove_digit(value: str) -> str:
    return re.sub(r'\d', '', value)


class TableView(QDialog):
    def __init__(self, dict_info: dict):
        super().__init__()
        self.dict_info = dict_info
        self.showMaximized()
        self.sheetlists = []
        self.sheetnames = []
        self.setWindowTitle("详情表格")
        for i in dict_info.keys():
            temp = os.path.split(i)[1]
            for j in dict_info[i]:
                self.sheetlists.append(pandas.read_excel(i, j, header=None))
                self.sheetnames.append(temp + '\n' + j)
        # 按钮布局
        layout = QVBoxLayout()
        layout1 = QGridLayout()
        start_button = QPushButton("开始")
        end_button = QPushButton("结束")
        account_button = QPushButton("账户")
        name_button = QPushButton("姓名")
        cash_button = QPushButton("金额")
        predict_button = QPushButton("预测")
        layout1.addWidget(account_button, 0, 0)
        layout1.addWidget(cash_button, 0, 1)
        layout1.addWidget(name_button, 0, 2)
        layout1.addWidget(predict_button, 1, 2)
        layout1.addWidget(start_button, 1, 0)
        layout1.addWidget(end_button, 1, 1)
        # 按钮槽函数
        start_button.clicked.connect(self.set_selectd_start_row)
        end_button.clicked.connect(self.set_selected_end_row)
        account_button.clicked.connect(self.set_account_column)
        cash_button.clicked.connect(self.set_cash_column)
        name_button.clicked.connect(self.set_name_column)
        predict_button.clicked.connect(self.predict)
        # 创建选项卡
        self.qtabwidget = QTabWidget()
        self.qtabwidget.setStyleSheet("QTabBar::tab { height: 100px}")
        self.qtabwidget.setTabsClosable(True)
        self.qtabwidget.tabCloseRequested.connect(self.tabClose)
        for i in range(len(self.sheetnames)):
            self.qtabwidget.addTab(self.createWidget(self.sheetlists[i]), self.sheetnames[i])
        layout.addWidget(self.qtabwidget)
        self.progressbar = QProgressBar()
        layout.addWidget(self.progressbar)
        layout.addLayout(layout1)
        # 数据校验
        check_button = QPushButton("校验数据")
        check_button.clicked.connect(self.verify)
        layout.addWidget(check_button)
        # 创建数据抽取按钮
        button = QPushButton("抽取数据")
        button.clicked.connect(self.extract_data)
        layout.addWidget(button)
        self.setLayout(layout)

    # 展示表格 核心
    def createWidget(self, index: pandas.DataFrame):
        wid = QWidget()
        layout = QVBoxLayout(wid)
        table_widget = QTableWidget()
        table_widget.setRowCount(index.shape[0])
        table_widget.setColumnCount(index.shape[1])
        table_widget.setStyleSheet("QTableWidget{gridline-color: black;}")
        index = index.astype(str)
        for row in range(index.shape[0]):
            for col in range(index.shape[1]):
                table_widget.setItem(row, col, QTableWidgetItem(str(index.iat[row, col]).replace(' ', '')))
        table_widget.setHorizontalHeaderLabels(['     ' for i in range(table_widget.columnCount())])
        table_widget.setVerticalHeaderLabels([str(i + 1).ljust(7, ' ') for i in range(table_widget.rowCount())])

        # 为表格添加右键菜单支持
        table_widget.setContextMenuPolicy(Qt.CustomContextMenu)
        table_widget.customContextMenuRequested.connect(
            lambda pos, tw=table_widget: self.showContextMenu(pos, tw)
        )

        layout.addWidget(table_widget)
        wid.setLayout(layout)
        return wid

    def createNewTableWidget(self, rows, cols):
        table_widget = QTableWidget(rows, cols)
        table_widget.setStyleSheet("QTableWidget{gridline-color: black;}")
        table_widget.setHorizontalHeaderLabels(['     ' for _ in range(cols)])
        table_widget.setVerticalHeaderLabels([str(i + 1).ljust(7, ' ') for i in range(rows)])

        # 为新表格添加右键菜单支持
        table_widget.setContextMenuPolicy(Qt.CustomContextMenu)
        table_widget.customContextMenuRequested.connect(
            lambda pos, tw=table_widget: self.showContextMenu(pos, tw)
        )

        return table_widget

    # 右键菜单核心逻辑
    def showContextMenu(self, position, table_widget):
        """在指定表格的指定位置显示右键菜单"""
        # 创建菜单
        menu = QMenu()

        # 获取当前选中的单元格位置
        current_row = table_widget.currentRow()
        current_col = table_widget.currentColumn()
        current_item = table_widget.currentItem()
        selected_items = table_widget.selectedItems()

        # 1. 复制单元格内容
        copy_action = QAction("复制内容", self)
        copy_action.setEnabled(current_item is not None)
        copy_action.triggered.connect(
            lambda: self.copyCellContent(table_widget, current_row, current_col)
        )
        menu.addAction(copy_action)

        # 分隔线
        menu.addSeparator()

        # 2. 插入行（在当前行上方）
        insert_row_action = QAction("插入行", self)
        insert_row_action.triggered.connect(
            lambda: table_widget.insertRow(current_row if current_row != -1 else table_widget.rowCount())
        )
        menu.addAction(insert_row_action)

        # 3. 删除当前行
        delete_row_action = QAction("删除当前行", self)
        delete_row_action.setEnabled(current_row != -1)
        delete_row_action.triggered.connect(
            lambda: table_widget.removeRow(current_row) if current_row != -1 else None
        )
        menu.addAction(delete_row_action)

        # 4. 删除选中的多行
        selected_rows = self.get_selected_rows(table_widget)
        delete_selected_action = QAction("删除选中行", self)
        delete_selected_action.setEnabled(len(selected_rows) > 0)
        delete_selected_action.triggered.connect(
            lambda: self.delete_selected_rows(table_widget, selected_rows)
        )
        menu.addAction(delete_selected_action)

        # 分隔线
        menu.addSeparator()

        # 5. 拆分选定区域到新选项卡（拆分后原区域会被移除）
        split_action = QAction("拆分选定区域到新选项卡（移除原区域）", self)
        split_action.setEnabled(len(selected_items) > 0)
        split_action.triggered.connect(
            lambda: self.split_selected_area(table_widget)
        )
        menu.addAction(split_action)

        # 分隔线
        menu.addSeparator()

        # 6. 编辑单元格
        edit_action = QAction("编辑单元格", self)
        edit_action.setEnabled(current_item is not None)
        edit_action.triggered.connect(
            lambda: table_widget.editItem(current_item) if current_item else None
        )
        menu.addAction(edit_action)

        # 7. 清空单元格
        clear_action = QAction("清空内容", self)
        clear_action.setEnabled(current_item is not None)
        clear_action.triggered.connect(
            lambda: current_item.setText("") if current_item else None
        )
        menu.addAction(clear_action)

        # 在鼠标位置显示菜单
        menu.exec_(table_widget.viewport().mapToGlobal(position))

    # 复制单元格内容到剪贴板
    def copyCellContent(self, table_widget, row, col):
        if row >= 0 and col >= 0:
            item = table_widget.item(row, col)
            if item:
                clipboard = QApplication.clipboard()
                clipboard.setText(item.text())

    # 获取所有选中的行（去重）
    def get_selected_rows(self, table_widget):
        selected_rows = set()
        for item in table_widget.selectedItems():
            selected_rows.add(item.row())
        return sorted(selected_rows)

    # 删除选中的多行
    def delete_selected_rows(self, table_widget, selected_rows):
        for row in sorted(selected_rows, reverse=True):
            table_widget.removeRow(row)
        self.draw_colunm_color()
        self.draw_row_color()

    # 拆分选定区域到新选项卡（修复单行删除问题）
    def split_selected_area(self, table_widget):
        """将选中的表格区域拆分到新的选项卡，并删除原表格中的对应区域"""
        selected_items = table_widget.selectedItems()
        if not selected_items:
            return

        # 确定选中区域的边界
        min_row = min(item.row() for item in selected_items)
        max_row = max(item.row() for item in selected_items)
        min_col = min(item.column() for item in selected_items)
        max_col = max(item.column() for item in selected_items)

        # 计算新表格的行数和列数
        new_rows = max_row - min_row + 1
        new_cols = max_col - min_col + 1

        # 创建新的表格窗口部件
        new_widget = QWidget()
        new_layout = QVBoxLayout(new_widget)

        # 创建新表格
        new_table = self.createNewTableWidget(new_rows, new_cols)

        # 复制选中区域的数据到新表格
        for row in range(min_row, max_row + 1):
            for col in range(min_col, max_col + 1):
                item = table_widget.item(row, col)
                if item:
                    new_item = QTableWidgetItem(item.text())
                    new_item.setBackground(item.background())
                    new_table.setItem(row - min_row, col - min_col, new_item)

        new_layout.addWidget(new_table)
        new_widget.setLayout(new_layout)

        # 获取当前选项卡名称
        current_tab_index = self.qtabwidget.currentIndex()
        current_tab_name = self.qtabwidget.tabText(current_tab_index)

        # 添加新选项卡
        new_tab_index = self.qtabwidget.addTab(new_widget, f"{current_tab_name} - 拆分区域")
        self.qtabwidget.setCurrentIndex(new_tab_index)

        # 修复核心：根据选择类型执行不同的删除逻辑
        # 1. 判断选择类型：单行、单列、矩形区域
        is_single_row = (min_row == max_row)
        is_single_col = (min_col == max_col)
        is_full_row = (min_col == 0 and max_col == table_widget.columnCount() - 1)

        # 2. 执行删除操作
        if is_single_row and is_full_row:
            # 情况1：选中完整一行 - 直接删除整行
            table_widget.removeRow(min_row)
        elif is_single_col:
            # 情况2：选中完整一列 - 直接删除整列
            table_widget.removeColumn(min_col)
        else:
            # 情况3：矩形区域（非整行整列）
            # 按行倒序删除单元格
            for row in range(max_row, min_row - 1, -1):
                # 按列倒序删除单元格
                for col in range(max_col, min_col - 1, -1):
                    table_widget.takeItem(row, col)

            # 如果是多行选择，删除选中的行
            if not is_single_row:
                for row in range(max_row, min_row - 1, -1):
                    table_widget.removeRow(row)
            # 如果是多列选择且不是单行，删除选中的列
            elif not is_single_col:
                for col in range(max_col, min_col - 1, -1):
                    table_widget.removeColumn(col)

        # 重新绘制表格颜色
        self.draw_colunm_color()
        self.draw_row_color()

    # 抽取数据
    def extract_data(self):
        total_cash = decimal.Decimal(0)
        error_info = []
        text = []
        flag = True
        for i in range(self.qtabwidget.count()):
            # 每个table_widget的提取参数不同
            start = -1
            end = -1
            account = -1
            cash = -1
            name = -1
            current_widget = self.qtabwidget.widget(i)
            current_qtablewidget = current_widget.layout().itemAt(0).widget()
            for j in range(current_qtablewidget.rowCount()):
                if '开始' in current_qtablewidget.verticalHeaderItem(j).text():
                    start = j
                if '结束' in current_qtablewidget.verticalHeaderItem(j).text():
                    end = j
            for j in range(current_qtablewidget.columnCount()):
                if current_qtablewidget.horizontalHeaderItem(j).text() == '账户':
                    account = j
                if current_qtablewidget.horizontalHeaderItem(j).text() == '金额':
                    cash = j
                if current_qtablewidget.horizontalHeaderItem(j).text() == '姓名':
                    name = j
            if start == -1 or end == -1 or account == -1 or cash == -1 or name == -1:
                error_info.append(str(self.qtabwidget.tabText(i)) + ',没有标记或者没有标记完全')
                flag = False
            else:
                for j in range(start, end + 1):
                    account_value = current_qtablewidget.item(j, account).text()
                    name_value = current_qtablewidget.item(j, name).text()
                    cash_value = current_qtablewidget.item(j, cash).text()
                    account_value = re.sub(r'\D', '', account_value)
                    name_value = str(name_value).replace(' ', '')
                    cash_value = str(cash_value).replace(' ', '')
                    text.append(account_value + '|' + name_value + '|' + cash_value)
                    try:
                        total_cash = decimal.Decimal(cash_value) + total_cash
                    except:
                        pass
        if flag:
            filepath, _ = QFileDialog.getSaveFileName(self, "文件保存", "/", "文本文件 (*.TXT)")
            if filepath != '':
                file = open(filepath, 'a')
                self.setWindowTitle("正在提取...")
                self.progressbar.setRange(0, len(text))
                self.progressbar.setValue(0)
                for i, j in zip(range(len(text)), text):
                    file.write(str(i + 1) + '|' + j)
                    file.write('\n')
                    self.progressbar.setValue(i + 1)
                file.close()
                UI_5.InfoMsg(f'提取成功,总计{total_cash}元,共{len(text)}个实体').exec_()
                self.close()
        else:
            window = UI_5.ErrorMsg(error_info)
            window.exec_()

    def predict(self):
        index_x = []
        index_y = []
        start = -1
        end = -1
        account = -1
        cash = -1
        name = -1
        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()
        current_qtablewidget.setHorizontalHeaderLabels(['     ' for i in range(current_qtablewidget.columnCount())])
        current_qtablewidget.setVerticalHeaderLabels(
            [str(i + 1).ljust(7, ' ') for i in range(current_qtablewidget.rowCount())])
        if current_qtablewidget.rowCount() <= 0 or current_qtablewidget.columnCount() <= 0:
            UI_5.ErrorMsg(['空表格']).exec_()
        else:
            for i in range(current_qtablewidget.rowCount()):
                for j in range(current_qtablewidget.columnCount()):
                    if len(remove_non_digit(str(current_qtablewidget.item(i, j).text()))) == 23 or len(
                            remove_non_digit(str(current_qtablewidget.item(i, j).text()))) == 19:
                        index_x.append(i)
                        index_y.append(j)
            start = index_x[0]
            end = index_x[-1]
            account = Counter(index_y).most_common(1)[0][0]
            index_x = []
            index_y = []
            index_y_temp = []
            for i in range(start, end + 1):
                for j in range(current_qtablewidget.columnCount()):
                    try:
                        f = float(current_qtablewidget.item(i, j).text())
                        if 1 < f < 1000000 or int(f) == 0:
                            index_y.append(j)
                    except:
                        pass
                    tempstr = remove_digit(str(current_qtablewidget.item(i, j).text()))
                    if 4 >= len(tempstr) >= 2 and tempstr != 'None':
                        index_y_temp.append(j)
            cash = Counter(index_y).most_common(1)[0][0]
            name = Counter(index_y_temp).most_common(1)[0][0]
            if start == -1 or end == -1 or account == -1 or cash == -1 or name == -1:
                UI_5.ErrorMsg(['提取失败']).exec_()
            else:
                if start == end:
                    current_qtablewidget.setVerticalHeaderItem(start, QTableWidgetItem("开始,结束"))
                else:
                    current_qtablewidget.setVerticalHeaderItem(start, QTableWidgetItem("开始"))
                    current_qtablewidget.setVerticalHeaderItem(end, QTableWidgetItem("结束"))
                current_qtablewidget.setHorizontalHeaderItem(account, QTableWidgetItem("账户"))
                current_qtablewidget.setHorizontalHeaderItem(name, QTableWidgetItem("姓名"))
                current_qtablewidget.setHorizontalHeaderItem(cash, QTableWidgetItem("金额"))
                for i in range(current_qtablewidget.rowCount()):
                    for j in range(current_qtablewidget.columnCount()):
                        item = current_qtablewidget.item(i, j)
                        item.setBackground(QBrush(QColor(255, 255, 255)))
                self.draw_colunm_color()
                self.draw_row_color()

    def verify(self):
        errinfo = []
        temp = decimal.Decimal(0)
        start = end = account = cash = name = -1
        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()

        current_qtablewidget.setStyleSheet("QTableWidget{border:10px solid green;gridline-color: green;}")

        for i in range(current_qtablewidget.rowCount()):
            if '开始' in current_qtablewidget.verticalHeaderItem(i).text():
                start = i
            if '结束' in current_qtablewidget.verticalHeaderItem(i).text():
                end = i
        for i in range(current_qtablewidget.columnCount()):
            if current_qtablewidget.horizontalHeaderItem(i).text() == '账户':
                account = i
            if current_qtablewidget.horizontalHeaderItem(i).text() == '金额':
                cash = i
            if current_qtablewidget.horizontalHeaderItem(i).text() == '姓名':
                name = i
        if start == -1 or end == -1 or account == -1 or cash == -1 or name == -1:
            UI_5.ErrorMsg(['当前选项卡没有标记或者没有标记完全']).exec_()
        else:
            for i in range(start, end + 1):
                if len(current_qtablewidget.item(i, account).text()) != 19 and len(
                        current_qtablewidget.item(i, account).text()) != 23:
                    errinfo.append(f'第{i + 1}行账户位数不对，或者为空')
                if remove_non_digit(current_qtablewidget.item(i, cash).text()) == '' or current_qtablewidget.item(i, cash).text() == 'nan':
                    errinfo.append(f'第{i + 1}行金额为空')
                if current_qtablewidget.item(i, name).text() == '' or current_qtablewidget.item(i, name).text() == 'nan':
                    errinfo.append(f'第{i + 1}行姓名为空')
            if len(errinfo) == 0:
                for i in range(start, end + 1):
                    try:
                        temp = decimal.Decimal(current_qtablewidget.item(i, cash).text()) + temp
                    except:
                        pass
                UI_5.InfoMsg(f'本页{end - start + 1}个数据，金额为{temp}').exec_()
            else:
                UI_5.ErrorMsg(errinfo).exec_()

    # 关闭选项卡功能
    def tabClose(self, index):
        self.qtabwidget.removeTab(index)

    # 选择开始行
    def set_selectd_start_row(self):
        previous_start = -1
        previous_end = -1
        previous_start_end = -1
        item1 = QTableWidgetItem("开始")
        item2 = QTableWidgetItem("开始,结束")
        item3 = QTableWidgetItem("结束")

        def item4(x):
            return QTableWidgetItem(str(x + 1).ljust(7, ' '))

        header = []
        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()
        for i in range(current_qtablewidget.rowCount()):
            if current_qtablewidget.verticalHeaderItem(i).text() in ['开始', '结束', '开始,结束']:
                header.append(current_qtablewidget.verticalHeaderItem(i).text())
            else:
                header.append(str(i + 1).ljust(7, ' '))
        current_qtablewidget.setVerticalHeaderLabels(header)
        for i in range(current_qtablewidget.rowCount()):
            if '开始' == current_qtablewidget.verticalHeaderItem(i).text():
                previous_start = i
            if '结束' == current_qtablewidget.verticalHeaderItem(i).text():
                previous_end = i
            if '开始,结束' == current_qtablewidget.verticalHeaderItem(i).text():
                previous_start_end = i
        # 直接写入
        if previous_start == -1 and previous_start_end == -1:
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item1)
        # 除去原先开始，写入新位置
        if previous_start != -1 and previous_start_end == -1 and current_qtablewidget.currentRow() != previous_start:
            current_qtablewidget.setVerticalHeaderItem(previous_start, item4(previous_start))
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item1)
        # 结束留原地，开始写新行
        if previous_start_end != -1 and current_qtablewidget.currentRow() != previous_start_end:
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item1)
            current_qtablewidget.setVerticalHeaderItem(previous_start_end, item3)
        # 写入开始,结束
        if previous_start == -1 and previous_end != -1 and previous_start_end == 1 and current_qtablewidget.currentRow() == previous_end:
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item2)
        # 除去原先开始，写入开始,结束
        if previous_start != -1 and previous_end != -1 and current_qtablewidget.currentRow() == previous_end:
            current_qtablewidget.setVerticalHeaderItem(previous_start, item4(previous_start))
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item2)
        # 全部设置白色
        for i in range(current_qtablewidget.rowCount()):
            for j in range(current_qtablewidget.columnCount()):
                item = current_qtablewidget.item(i, j)
                item.setBackground(QBrush(QColor(255, 255, 255)))
        self.draw_colunm_color()
        self.draw_row_color()

    # 选择结束行
    def set_selected_end_row(self):
        previous_start = -1
        previous_end = -1
        previous_start_end = -1
        header = []
        item1 = QTableWidgetItem("开始")
        item2 = QTableWidgetItem("开始,结束")
        item3 = QTableWidgetItem("结束")

        def item4(x):
            return QTableWidgetItem(str(x + 1).ljust(7, ' '))

        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()
        for i in range(current_qtablewidget.rowCount()):
            if current_qtablewidget.verticalHeaderItem(i).text() in ['开始', '结束', '开始,结束']:
                header.append(current_qtablewidget.verticalHeaderItem(i).text())
            else:
                header.append(str(i + 1).ljust(7, ' '))
        for i in range(current_qtablewidget.rowCount()):
            if '开始' == current_qtablewidget.verticalHeaderItem(i).text():
                previous_start = i
            if '结束' == current_qtablewidget.verticalHeaderItem(i).text():
                previous_end = i
            if '开始,结束' == current_qtablewidget.verticalHeaderItem(i).text():
                previous_start_end = i
        # 直接写入结束
        if previous_end == -1 and previous_start_end == -1:
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item3)
        # 除去原先结束，写入新位置
        if previous_end != -1 and previous_start_end == -1 and current_qtablewidget.currentRow() != previous_end:
            current_qtablewidget.setVerticalHeaderItem(previous_end, item4(previous_end))
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item3)
        # 开始留原地，结束写新行
        if previous_start_end != -1 and current_qtablewidget.currentRow() != previous_start_end:
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item3)
            current_qtablewidget.setVerticalHeaderItem(previous_start_end, item1)
        # 写入开始,结束
        if previous_end == -1 and previous_start != -1 and previous_start_end == 1 and current_qtablewidget.currentRow() == previous_start:
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item2)
        # 除去原先结束，写入开始, 结束
        if previous_start != -1 and previous_end != -1 and current_qtablewidget.currentRow() == previous_start:
            current_qtablewidget.setVerticalHeaderItem(previous_end, item4(previous_end))
            current_qtablewidget.setVerticalHeaderItem(current_qtablewidget.currentRow(), item2)
        # 全部设置白色
        for i in range(current_qtablewidget.rowCount()):
            for j in range(current_qtablewidget.columnCount()):
                item = current_qtablewidget.item(i, j)
                item.setBackground(QBrush(QColor(255, 255, 255)))
        self.draw_colunm_color()
        self.draw_row_color()

    # 选择账户列
    def set_account_column(self):
        item1 = QTableWidgetItem("账户")
        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()
        for i in range(current_qtablewidget.columnCount()):
            if current_qtablewidget.horizontalHeaderItem(i).text() == '账户':
                for ro in range(current_qtablewidget.rowCount()):
                    item = current_qtablewidget.item(ro, i)
                    item.setBackground(QBrush(QColor(255, 255, 255)))
                item = QTableWidgetItem('     ')
                current_qtablewidget.setHorizontalHeaderItem(i, item)
        current_qtablewidget.setHorizontalHeaderItem(current_qtablewidget.currentColumn(), item1)
        # 全部设置白色
        for i in range(current_qtablewidget.rowCount()):
            for j in range(current_qtablewidget.columnCount()):
                item = current_qtablewidget.item(i, j)
                item.setBackground(QBrush(QColor(255, 255, 255)))
        self.draw_row_color()
        self.draw_colunm_color()

    # 选择钱数列
    def set_cash_column(self):
        item1 = QTableWidgetItem("金额")
        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()
        for i in range(current_qtablewidget.columnCount()):
            if current_qtablewidget.horizontalHeaderItem(i).text() == '金额':
                for ro in range(current_qtablewidget.rowCount()):
                    item = current_qtablewidget.item(ro, i)
                    item.setBackground(QBrush(QColor(255, 255, 255)))
                item = QTableWidgetItem('     ')
                current_qtablewidget.setHorizontalHeaderItem(i, item)
        current_qtablewidget.setHorizontalHeaderItem(current_qtablewidget.currentColumn(), item1)
        # 全部设置白色
        for i in range(current_qtablewidget.rowCount()):
            for j in range(current_qtablewidget.columnCount()):
                item = current_qtablewidget.item(i, j)
                item.setBackground(QBrush(QColor(255, 255, 255)))
        self.draw_row_color()
        self.draw_colunm_color()

    # 选择姓名列
    def set_name_column(self):
        item1 = QTableWidgetItem("姓名")
        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()
        for i in range(current_qtablewidget.columnCount()):
            if current_qtablewidget.horizontalHeaderItem(i).text() == '姓名':
                for ro in range(current_qtablewidget.rowCount()):
                    item = current_qtablewidget.item(ro, i)
                    item.setBackground(QBrush(QColor(255, 255, 255)))
                item = QTableWidgetItem('     ')
                current_qtablewidget.setHorizontalHeaderItem(i, item)
        current_qtablewidget.setHorizontalHeaderItem(current_qtablewidget.currentColumn(), item1)
        # 全部设置白色
        for i in range(current_qtablewidget.rowCount()):
            for j in range(current_qtablewidget.columnCount()):
                item = current_qtablewidget.item(i, j)
                item.setBackground(QBrush(QColor(255, 255, 255)))
        self.draw_row_color()
        self.draw_colunm_color()

    # 表格绘色
    def draw_row_color(self):
        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()
        # 实时渲染
        for i in range(current_qtablewidget.rowCount()):
            if current_qtablewidget.verticalHeaderItem(i).text() == '开始':
                for col in range(current_qtablewidget.columnCount()):
                    item = current_qtablewidget.item(i, col)
                    item.setBackground(QBrush(QColor(0, 47, 167, 50)))
                    item.setSelected(False)
            if current_qtablewidget.verticalHeaderItem(i).text() == '结束':
                for col in range(current_qtablewidget.columnCount()):
                    item = current_qtablewidget.item(i, col)
                    item.setBackground(QBrush(QColor(129, 216, 207, 50)))
                    item.setSelected(False)
            if current_qtablewidget.verticalHeaderItem(i).text() == '开始,结束':
                for col in range(current_qtablewidget.columnCount()):
                    item = current_qtablewidget.item(i, col)
                    item.setBackground(QBrush(QColor(230, 0, 0, 175)))
                    item.setSelected(False)

    # 表格绘色
    def draw_colunm_color(self):
        current_index = self.qtabwidget.currentIndex()
        current_widget = self.qtabwidget.widget(current_index)
        current_qtablewidget = current_widget.layout().itemAt(0).widget()
        for i in range(current_qtablewidget.columnCount()):
            if current_qtablewidget.horizontalHeaderItem(i).text() == '账户':
                for ro in range(current_qtablewidget.rowCount()):
                    item = current_qtablewidget.item(ro, i)
                    item.setBackground(QBrush(QColor(176, 89, 35, 50)))
                    item.setSelected(False)
            if current_qtablewidget.horizontalHeaderItem(i).text() == '金额':
                for ro in range(current_qtablewidget.rowCount()):
                    item = current_qtablewidget.item(ro, i)
                    item.setBackground(QBrush(QColor(230, 0, 0, 50)))
                    item.setSelected(False)
            if current_qtablewidget.horizontalHeaderItem(i).text() == '姓名':
                for ro in range(current_qtablewidget.rowCount()):
                    item = current_qtablewidget.item(ro, i)
                    item.setBackground(QBrush(QColor(1, 132, 127, 50)))
                    item.setSelected(False)

if __name__ == '__main__':
    dict_info = {'C:/Users/kioutily/Desktop/银行工程文件/工资代发2.0/2024年6月13日打卡在职乡镇补贴、提租补贴及退休教师6月份提租补贴和基础绩效奖花名册.xls':['Sheet1']}
    app = QApplication(sys.argv)
    mainwindows = TableView(dict_info=dict_info)
    mainwindows.show()
    sys.exit(app.exec_())


